<?php

namespace app\api\controller;

use app\admin\controller\card\Card;
use app\admin\model\card\Carduser;
use app\admin\model\gift\Gift;
use app\admin\model\teacher\Share;
use app\admin\model\teacher\Teacher;
use app\common\controller\Api;
use app\common\model\User;
use think\Db;

class Indexs extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 转增书券
     * @ApiMethod (GET)
     * @param string money 书券数量
     * @param string mobile 转赠用户手机号
     * @author 杜洋
     **/
    public function givemoney()
    {
        $token = $this->auth->getToken();
        $money = $this->request->get('money');
        $this->error('暂未开放');
        $mobile = $this->request->get('mobile');
        $password = $this->request->get('password');
        $uid = $this->getToken($token);
        $User = new User();
        $userInfo = $User->field('id,score,money,nickname,pay_pass,pid')->find($uid);
//        halt($userInfo['money']);
        $userInfo2 = $User->field('id,score,money,nickname')->where('mobile', $mobile)->find();
        if ($userInfo['money'] < $money) {
            $this->error('书券余额不足');
        }
        if ($userInfo2['id'] == $uid) {
            $this->error('不能转赠自己');
        }
        //验证交易密码
//            halt($userInfo['pay_pass']);
//        if ($userInfo['pay_pass'] != $password) {
//            $this->error('交易密码错误');
//        }
        $deductMoney = null;
        //查询有多少
        //直推下级
        $count = (new User())->where(['pid' => $uid])->field('id')->count();
        //转赠规则
        $data = (new Gift())->field('id,criteria,value,desc')->select()->toArray();
        $datacriteria = array_column($data, 'criteria');
//        halt($datacriteria);
        $datavalue = array_column($data, 'value');
//        halt($count);
        if ($count <= $datacriteria[0]) {
            //扣除的书券
            $deductMoney = $money / $datavalue[0];
        }
        if ($count >= 4) {
            foreach ($datacriteria as $index => $criteria) {
                if ($count < $criteria) {
                    //扣除的书券
                    $deductMoney = $money / (1 - $datavalue[$index - 1]);
                    break;
                }
            }
        }
        if (end($datacriteria) <= $count) {
            //扣除的书券
            $deductMoney = $money / (end($datavalue));
        }
//        $this->success('', $deductMoney - $money);
        $bonus = (new Teacher())->field('bonus')->select();
        //取所有的bonus
        $totalBonus = 0;
        $one = []; // 初始化一个空数组来存储每个计算结果
        foreach ($bonus as $k => $item) {
            $totalBonus += $item['bonus'];
            $one[] = $item['bonus'] * ($deductMoney - $money); // 将计算结果添加到数组中
        }
//        $this->success($one);
        $currentMoney = DB::table('fa_book_bonus')
            ->field('money_one,money_two,money_three,money_four,money_five')
            ->find();
        DB::table('fa_book_bonus')
            ->where('id', 1)
            ->update(['money_one' => $currentMoney['money_one'] + $one[0], 'money_two' => $currentMoney['money_two'] + $one[1], 'money_three' => $currentMoney['money_three'] + $one[2], 'money_four' => $currentMoney['money_four'] + $one[3], 'money_five' => $currentMoney['money_five'] + $one[4]]);
        Db::startTrans();
        User::money(-$deductMoney, $uid, '转增用户' . $userInfo2['nickname'] . '扣除');
        User::money(+$money, $userInfo2['id'], '用户' . $userInfo['nickname'] . '转增获得');
        Db::commit();
        $this->success('转赠成功', '转赠金额:' . $money . ' 扣除金额:' . $deductMoney . ' 实际转增金额:' . $money);
    }

    /**
     * @ApiMethod (GET)
     * 定时分红
     */
    public function bonus()
    {
        //查询等级用户和数量
        $shareData = (new Share())->where('teacher_id', '>', 0)->field('id,user_id,teacher_id')->select();
        $teacherData = (new Teacher())->field('id,name')->order('weigh', 'asc')->select();
        $currentMoney = DB::table('fa_book_bonus')
            ->field('money_one,money_two,money_three,money_four,money_five')
            ->find();
        try {
            $users = [];
            foreach ($shareData as $item) {
                foreach ($teacherData as $teacher) {
                    if ($teacher['id'] == $item['teacher_id']) {
                        $users[$teacher['name']][] = $item['user_id'];
                        break;
                    }
                }
            }
//            print_r($users);
            // 调整键的顺序
            $keys = array_keys($users);
            $sortedKeys = ["青铜观阅师", "白银观阅师", "黄金观阅师", "钻石观阅师", "王者观阅师"];
            $sortedData = [];
            // 根据调整后的顺序重新索引数组元素
            foreach ($sortedKeys as $key) {
                if (in_array($key, $keys)) {
                    $sortedData[$key] = $users[$key];
                    unset($keys[array_search($key, $keys)]); // 从原始键数组中移除已使用的键
                }
            }
            //每个等级的用户数量
            $countValue = [];
            //每个等级的用户id
            //每个等级的奖池金额
            $countMoney = [];
            foreach ($sortedData as $key => $value) { //3
                $countValue[] = count($value);
            }
//            halt($countValue);
            foreach ($currentMoney as $k => $v) {
                $countMoney[] = $v;
            }
//            print_r($countMoney);
            //每个等级里的用户分得的金额
            $results = [];
            foreach ($countValue as $index => $value) {
                $money = (float)str_replace(",", ".", $countMoney[$index]);
                $result = $money / $value;
                $results[] = $result;
            }
//            halt($results);
            //开始分配金额
            $usersId = 0;
            $moneyId = 0;
            foreach ($sortedData as $key => $value) {
                foreach ($value as $item) {
                    User::money(+floatval($results[$moneyId]), $item, '书券分红');
                    //扣除奖池
                    $usersId++;
                }
                $moneyId++;
            }
            DB::table('fa_book_bonus')
                ->where('id', 1)
                ->update([
                    'money_one' => DB::raw('money_one - ' . $results[0] * $countValue[0]),
                    'money_two' => DB::raw('money_two - ' . $results[1] * $countValue[1]),
                    'money_three' => DB::raw('money_three - ' . $results[2] * $countValue[2]),
                    'money_four' => DB::raw('money_four - ' . $results[3] * $countValue[3]),
                    'money_five' => DB::raw('money_five - ' . $results[4] * $countValue[4])
                ]);
        } catch (\Exception $e) {
            Db::rollback();
        }
        $this->success('成功', $results);
    }

    /**
     * 赠送体验包
     */
    public function getViewCard()
    {
        //接收手机号
        $mobile = $this->request->post('mobile/d');
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $exper_number = User::where('id', $uid)->value('exper_number');
        if ($exper_number <= 0) {
            $this->error('体验包数量不足！');
        }
        //验证手机号是否存在
        $userInfo = User::where('mobile', $mobile)->find();
        if (!$userInfo) {
            $this->error('用户不存在!');
        }
        //验证受赠人是否有观阅包
        $isCard = Db::table('fa_view_card_user')->where('user_id', $userInfo['id'])->find();
        if ($isCard) {
            $this->error('该用户不符合赠送规则');
        }
        $order_data = [
            'user_id' => $userInfo['id'],
            'card_id' => 1,
            'card_type' => 3,
            'day_count' => 30,
            'day_now' => 1,
            'day_no' => 29,
            'starttime' => time(),
            'endtime' => time() + 2592000,
            'addtime' => time()
        ];
        $share = new Share();
        $card = new \app\admin\model\card\Card();
        $userCard = $card->where('id', 1)->field('active')->find();
        try {
            Db::table('fa_user')->where('id', $uid)->update(['exper_number' => $exper_number - 1]);
            Db::startTrans();
            Db::table('fa_view_card_user')->insertGetId($order_data);
            $share->where('user_id', $userInfo['id'])->setInc('active_zong', $userCard['active']);
            $share->where('user_id', $userInfo['id'])->setInc('active_ge', $userCard['active']);
            $share->where('user_id', $userInfo['pid'])->setInc('active_zong', $userCard['active']);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('赠送失败');
        }
        $this->success('赠送成功');
    }

    /**
     *活跃值查询 首页
     * @ApiMethod (GET)
     */
    public function getActive()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $share = new Share();
        $shareActive = $share->where('user_id', $uid)->field('active_zong')->select();
        $User = new User();
        $userInfo = $User->field('id,avatar,nickname,jointime')->where(['pid' => $uid])->select()->toArray();
        $userInfo1 = $User->where(['id' => $uid])->field('id,avatar,nickname,jointime')->find();
        $userCount = count($userInfo);
        $ids_to_check = array_column($userInfo, 'id');//直推用户的user_id
        $userInfo2 = $User->field('id,pid')->where(['id' => $uid])->select()->toArray();

        $userInfo4 = $User->field('id,avatar,nickname,username')->where(['id' => $userInfo2[0]['pid']])->select()->toArray();
        $userData = [];
        foreach ($ids_to_check as $k => $item) { //直推用户的数据
            $userData[] = $User->with('active')->field('id,nickname, avatar, createtime')->where('id', $item)->select()->toArray();//下级用户
        }
        foreach ($userData as $key => $item) {
            if (isset($item[0]['createtime']) && is_numeric($item[0]['createtime'])) {
                $userData[$key][0]['createtime'] = date('Y-m-d H:i:s', $item[0]['createtime']);
            }
        }
//        $data = [];
        $date = date('Y-m-d H:i:s', $userInfo1['jointime']);
        $data1 = [];
        foreach ($shareActive as $key => $item) {
            $data1[] = $shareActive[$key]['active_zong'];
        }
//        $this->success('',$data1);
        $this->success('成功', ['userInfo' => $userInfo1,//用户信息
            'userActive' => $data1, //活跃值
            'userCount' => $userCount, //粉丝数量
            'inviter' => $userInfo4,//我的邀请人
            'invite' => $date,//邀请时间
            'userCountList' => $userData//下级用户信息
        ]);
    }

    /**
     * 活跃值查询大区
     * @ApiMethod (GET)
     */
    public function getActiveMax()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
//        $this->success($uid);
//        //查询有多少直推下级
        $User = new User();
        $userInfo = $User->field('id')->where(['pid' => $uid])->select()->toArray();
        $ids_to_check = array_column($userInfo, 'id');//直推用户的user_id
//        $this->success('',$ids_to_check);
        $share = new Share();
        $shareData = [];
        foreach ($ids_to_check as $k => $item) { //直推用户的数据
            $shareData[] = $share->field('id,user_id,active_zong,active_qu,all_children')->where('user_id', $item)->select()->toArray();//下级用户
        }
        $maxChildren = 0;
        $maxArray = [];
        foreach ($shareData as $item) {
            $counts[] = count($item);
            //求大区
            if (count($item) > 0 && isset($item[0]['all_children']) && $item[0]['all_children'] > $maxChildren) {
                $maxArray = $item;//最大
                $maxChildren = $item[0]['all_children'];
            }
        }
        // 大区的用户id
//        $this->success('',$shareData);
        $max = [];
        if (empty($maxArray)) { //没有最大值
            if (!empty($shareData)) {
                foreach ($shareData as $k => $item) {
                    foreach ($item as $k1 => $item1) {
                        $max = $item1['user_id'];
                    }
                }
            } else {
                $max = -1;
            }
        } else {
            $max = $maxArray[0]['user_id'];
        }
//        $this->success($max);
        $userItemInfo = $User->field('id,avatar,nickname')->where(['pid' => $max])->select()->toArray();
//        $this->success($userItemInfo);
        $userInfo0 = $User->field('id,avatar,nickname')->where(['id' => $max])->select()->toArray();
        $userInfo1 = $share->where('user_id', $max)->field('active_zong,all_children')->select();
        $shareActive = $share->where('user_id', $uid)->field('active_zong')->select();
//        $this->success($userItemInfo);
        foreach ($userItemInfo as $k => $item) {
            $userItemInfo[$k]['active_zong'] = $share->where('user_id', $item['id'])->field('active_zong')->select();
        }
//        $this->success($userItemInfo);
        $this->success('', [
            'userActiveCount' => $shareActive,//总活跃
            'nowActiveInfo' => $userInfo0,//支线
            'maxActive' => $userInfo1,//大区活跃度
            'maxCount' => count($userItemInfo),//大区人数
            'maxUserInfo' => $userItemInfo]);//大区用户信息
    }

    /**
     * 活跃值查询小区
     *
     */
    public function getActiveMin()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
//        //查询有多少直推下级
        $User = new User();
        $userInfo = $User->field('id')->where(['pid' => $uid])->select()->toArray();
        $ids_to_check = array_column($userInfo, 'id');//直推用户的user_id
        $share = new Share();
        $shareData = [];
        foreach ($ids_to_check as $k => $item) { //直推用户的数据
            $shareData[] = $share->field('id,user_id,active_zong,active_qu,all_children')->where('user_id', $item)->select()->toArray();//下级用户
        }
        $maxChildren = 0;
        foreach ($shareData as $item) {
            $counts[] = count($item);
            //求大区
            if (count($item) > 0 && isset($item[0]['all_children']) && $item[0]['all_children'] > $maxChildren) {
                $maxChildren = $item[0]['all_children'];
            }
        }
        $userIds = [];
        foreach ($shareData as $group) {
            foreach ($group as $item) {
                if (isset($item['user_id']) && $item['user_id'] != 91) {
                    $userIds[] = $item['user_id'];
                }
            }
        }
        // 小区的用户id
        $shareActive = [];
        $userInfo2 = [];
        $userInfo1 = [];
        foreach ($userIds as $k => $item) {
            //用户头像
            $userInfo1[] = $User->field('id,pid,avatar,nickname')->where(['pid' => $item])->select()->toArray();
            //用户活跃度
            $userInfo2[] = $share->where('user_id', $item)->field('active_zong,all_children')->select();
            $shareActive[] = $share->where('user_id', $item)->field('active_zong')->select();
        }
        $minUserActive = 0;
        foreach ($shareActive as $k => $item) {
            $minUserActive += $item[0]['active_zong'];
        }
        $minActive = 0;
        $minCount = 0;
        foreach ($userInfo2 as $k => $item) {
//            $userInfo1[$k][0]['active_zong'] = $item[0]['active_zong'];
            $minActive += $item[0]['active_zong'];
            $minCount += $item[0]['all_children'];
        }
        $array = array_map(function ($userSubArray) {
            if (!empty($userSubArray)) {
                return array_map(function ($user) {
                    $user['active_zong'] = 0;
                    return $user;
                }, $userSubArray);
            }
            return $userSubArray; // 返回原样空数组
        }, $userInfo1);
//        $this->success('',$array);
        $count = 0;
        foreach ($userInfo1 as $subArray) {
            foreach ($subArray as $item) {
                if (is_array($item) && count($item) > 0) { // 检查是否为非空关联数组
                    $count++;
                }
            }
        }
        $this->success('', [
            'userActiveCount' => $minUserActive,//总活跃
            'minActive' => $minActive,
            'minCount' => $count,
            'maxUserInfo' => $array]);
    }

    /**
     *HHC
     */
    public function getHHC()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $user = new User();
        $data = $user->where(['id' => $uid])->field('id,exper_number')->find();
        $this->success('成功', $data);
    }

    /**
     * 转赠规则手续费
     */
    public function getShareFee()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $gift = new Gift();
        //我的直推人数
        $userCount = (new User())->where(['pid' => $uid])->field('id')->count();
        //规则
        $giftRules = (new Gift())->field('id,criteria,value')->select()->toArray();
        // 根据直推人数找到符合条件的奖励
        $datacriteria = array_column($giftRules, 'criteria');
        $datavalue = array_column($giftRules, 'value');
//        halt($count);
        if ($userCount <= $datacriteria[0]) {
            //扣除的书券
            $deductMoney = $datavalue[0];
        }
        if ($userCount >= 4) {
            foreach ($datacriteria as $index => $criteria) {
                if ($userCount < $criteria) {
                    //扣除的书券
                    $deductMoney = $datavalue[$index - 1];
                    break;
                }
            }
        }
//        halt($deductMoney);
        if (end($datacriteria) <= $userCount) {
            //扣除的书券
            $deductMoney = (end($datavalue));
        }
        $this->success('', $deductMoney * 100 . '%');


    }

    public function zsya()
    {
        $id = 136;
        function getDescendants($id)
        {
            $users = User::where('pid', $id)->select(['id'])->toArray();
            $descendants = collect($users);

            foreach ($users as $user) {
                $descendants = $descendants->merge(getDescendants($user->id));
            }

            return $descendants;
        }

        $allDescendants = getDescendants($id);
        $this->success('', $allDescendants);
    }

    /**
     * 读取手机号,批量赠送阅读包
     */
    public function getPhone()
    {
        // 定义文件路径
        $file_path = 'C:\Users\Administrator\Desktop/iphone.txt';
        // 检查文件是否存在并可读
        $phone_numbers = [];
        if (file_exists($file_path) && is_readable($file_path)) {
            // 用 file 函数读取文件内容，每一行会作为数组的一个元素
            $phone_numbers = file($file_path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            // 去除可能存在的换行符或其他空白字符
            foreach ($phone_numbers as &$number) {
                $number = trim($number);
            }
        } else {
            $this->error("文件不存在");
        }
        // 删除重复的手机号码
        $unique_phone_numbers = array_unique($phone_numbers);
        //订单数据
        $order_data = [];
        //已有体验包用户手机号
        $existingCardUserIds = [];
        //未注册的手机号
        $unfoundPhoneNumbers = [];
        foreach ($unique_phone_numbers as $number1) {
            // 使用当前循环变量查询对应的用户 ID
            $user = User::where(['mobile' => $number1])->field('id')->find();
            if (is_null($user)) {
                $unfoundPhoneNumbers[] = $number1;
            } else {
                // 若无体验包，则添加订单数据
                $order_data[] = [
                    'user_id' => $user->id,
                    'card_id' => 1,
                    'card_type' => 3,
                    'day_count' => 30,
                    'day_now' => 1,
                    'day_no' => 29,
                    'starttime' => time(),
                    'endtime' => time() + 2592000,
                    'addtime' => time(),
                    'created_by' => '杜洋'
                ];

            }
        }
//        $this->success('成功', [
//            "未注册" => $unfoundPhoneNumbers,
//            "已有体验包手机号" => $existingCardUserIds,
//            "有效手机号数量" => count($order_data),
//            "总数" => count($order_data) + count($existingCardUserIds) + count($unfoundPhoneNumbers)]);
        foreach ($order_data as $k1 => $item) {
            $a = Db::table('fa_view_card_user')->insertGetId($item);
        }
        $this->success('成功', [
            "未注册" => $unfoundPhoneNumbers,
            "已有体验包手机号" => $existingCardUserIds,
            "有效手机号数量" => count($order_data),
            "总数" => count($order_data) + count($existingCardUserIds) + count($unfoundPhoneNumbers)]);
    }
    //删除
    public function deleteCard()
    {
        $id = 1;
        $card = new Card();
        $card->where('id', $id)->delete();
    }

    /**
     * 查出每人有多少观阅包
     */
    public function getCardUser()
    {
        $user = (new User())->field('id,mobile')->order('id', 'asc')->select()->toArray();

        foreach ($user as $k1 => $item) {
            $cardUsers = (new Carduser())
                ->where(['user_id' => $item['id']])
                ->with('card')
                ->field('user_id,card_id')
                ->select()
                ->toArray();

            $user[$k1]['carduser'] = array_map(function ($cardUser) {
                return [
                    'user_id' => $cardUser['user_id'],
                    'card_name' => $cardUser['card']['name']
                ];
            }, $cardUsers);
        }

        $this->success('', $user);
    }

}